package com.youease.chris.view.mediator
{
	import com.youease.chris.control.CreateMapCommand;
	import com.youease.chris.model.vo.MapData;
	import com.youease.chris.view.CreateMapTitleWindow;
	import com.youease.chris.model.proxy.*;
	import com.youease.chris.model.vo.*;
	import com.youease.chris.manager.GlobalObject;
	import com.youease.chris.utils.Common;
	
	import flash.events.MouseEvent;
	
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	public class CreateMapMediator extends Mediator implements IMediator
	{
		public static const NAME:String = "CreateMapMediator";
		public static var INDEX:int = 0;
		
		private var mapData:MapData;
		
		public function CreateMapMediator(viewComponent:Object)
		{
			super(NAME+INDEX, viewComponent);
			createMap.create.addEventListener(MouseEvent.CLICK,onCreateMap);
			INDEX++;
		}
		
		public function onCreateMap(evt:MouseEvent):void {
			mapData = new MapData(createMap.mapName.text);
			mapData.type = createMap.mapType.selectedValue as int;
			mapData.mapRows = createMap.mapRows.value;
			mapData.mapCols = createMap.mapCols.value;
			mapData.tileWidth = createMap.tileWidth.value;
			mapData.tileHeight = createMap.tileHeight.value;
			
			for(var i:int=0;i<mapData.mapRows;i++) {
				for(var j:int=0;j<mapData.mapCols;j++) {
					mapData.crossData[i+","+j] = true;
				}
			}
			
			if(!mapData.name||Common.trim(mapData.name)=="") {
				trace("地图名不能为空");
				createMap.nameError.visible = true;
				return;
			}
			
			(this.facade.retrieveProxy(ProjectDataProxy.NAME) as ProjectDataProxy).addMap(mapData);
			var defaultLayer:LayerData = new LayerData(mapData.name+"_"+"background",mapData);
			GlobalObject.currentLayer = defaultLayer.name;
			
			var defaultLayerProxy:LayerDataProxy = new LayerDataProxy(defaultLayer);
			var mapDataProxy:MapDataProxy = new MapDataProxy(mapData);
			
			mapDataProxy.addLayer(defaultLayer);
			
			this.facade.registerProxy(defaultLayerProxy);
			this.facade.registerProxy(mapDataProxy);
			
			sendNotification(CreateMapCommand.CREATE_MAP,mapDataProxy);
		}
		
		override public function listNotificationInterests():Array {
			return [
				CreateMapCommand.CREATE_MAP_COMPLETE
			];
		}
		
		override public function handleNotification(notification:INotification):void {
			switch(notification.getName()) {
				case CreateMapCommand.CREATE_MAP_COMPLETE:
					createMap.closeWindow();
					break;
			}
		}
		
		public function get createMap():CreateMapTitleWindow {
			return this.viewComponent as CreateMapTitleWindow;
		}
	}
}